<#ibizinclude>
./CONTROL-BASE.template.ftl
</#ibizinclude>

<#ibizinclude>
../@MACRO/CONTROL/CONTROL_HEADER-BASE.vue.ftl
</#ibizinclude>

    /**
     * 视图类型
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected viewType?: string | 'DEMOBMDVIEW' | 'DEMOBMDVIEW9' | 'DEMOBWFMDVIEW';

    /**
     * 显示处理提示
     *
     * @type {boolean}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop({ default: true }) protected showBusyIndicator?: boolean;

    /**
     * 部件行为--update
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected updateAction!: string;
    
    /**
     * 部件行为--fetch
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected fetchAction!: string;
    
    /**
     * 部件行为--remove
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected removeAction!: string;
    
    /**
     * 部件行为--load
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected loadAction!: string;
    
    /**
     * 部件行为--loaddraft
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected loaddraftAction!: string;
    
    /**
     * 部件行为--create
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected createAction!: string;

    /**
     * 部件样式
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop({default: '<#if ctrl.getMobListStyle?? && ctrl.getMobListStyle()??>${ctrl.getMobListStyle()}</#if>'}) protected controlStyle!: string | 'ICONVIEW'  | 'LISTVIEW' | 'SWIPERVIEW' | 'LISTVIEW2' | 'LISTVIEW3' | 'LISTVIEW4';

    /**
    *上级传递的选中项
    *@type {Array}
    *@memberof ${srfclassname('${ctrl.codeName}')}
    */
     @Prop() public selectedData?:Array<any>;


    /**
    * 新建打开视图
    *
    * @type {Function}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    @Prop() public newdata?: Function; 


    /**
    * 打开视图
    *
    * @type {Function}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    @Prop() public opendata?: Function; 


    /**
    * 当前选中数组
    *
    * @type {array}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public  selectdata :any = [];

    /**
    * 关闭行为
    *
    * @type {Function}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    @Prop() public close?:Function;


    /**
    * 是否为临时模式
    *
    * @type {boolean}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    @Prop({ default: false}) public isTempMode?:boolean;

    /**
    * 是否正在加载
    *
    * @type {boolean}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public isLoading:boolean = true;

    /**
    * 存放多数据选择数组（多选）
    *
    * @type {array}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public checkboxList:Array<string> = [];

    /**
    * 存放数据选择数组(单选)
    *
    * @type {object}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public radio:any = '';


    /**
    * 点击多选按钮触发
    *
    *
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public change(){
        if(this.isMutli){
             let checkboxLists= this.items.filter((item,index)=>{
                  if(this.checkboxList.indexOf(item.srfkey)!=-1){
                    return true;
                  }else{
                    return false;
                  }
                })
          this.$emit('selectchange',checkboxLists);
        }else{
           let radioItem = this.items.filter((item,index)=>{return item.srfkey==this.radio});
           this.$emit('selectchange',radioItem);
        }
    }

    /**
    * 列表键值对
    *
    * @type {Map}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public listMap: any = new Map();

    /**
    * 分页大小
    *
    * @type {number}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public pageSize: number = ${ctrl.getPagingSize()?c};

    /**
    * 总页数
    *
    * @type {number}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
     public pageTotal: number = 0;

    /**
    * 当前页数
    *
    * @type {number}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
     public pageNumber: number = 1;

    /**
    * 判断底部数据是否全部加载完成，若为真，则 bottomMethod 不会被再次触发
    *
    * @type {number}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    get allLoaded() {
        return ((this.pageNumber + 1) * this.pageSize) >= this.pageTotal ? true : false;
    }

    /**
    * 底部状态
    *
    * @type {String}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    // public bottomStatus: String = "";

    /**
    * 顶部状态
    *
    * @type {String}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    // public topStatus: String = "";

    /**
    * 
    *
    * @type {Number}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    // public moveTranslate: Number = 0;

    /**
    * searchKey 搜索关键字
    *
    * @type {string}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
     public searchKey:string = '';

    /**
    * 列表数组
    *
    * @param {Array<any>}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public items:Array<any> =[];

    /**
    * 选中数组
    *
    * @param {Array<any>}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public selectedArray:Array<any> = [];

    /**
    * 多选计数
    *
    * @param {number}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public selectednumber:number =0;

    /**
    * 搜索行为
    *
    * @param {string}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    @Prop() public searchAction?:string;

    /**
    * 是否为选择视图
    *
    * @param {boolean} 
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    @Prop() public isSelected?:boolean;

    /**
    * 是否多选
    *
    * @type {boolean}
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    @Prop({default:false}) public isMutli?: boolean;

    /**
    * 单选选择值
    *
    * @param {string} 
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public selectedValue:string = ""; 

    /**
    * 部件排序对象
    *
    * @param {object} 
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public sort: any = { <#if ctrl.isNoSort?? && ctrl.isNoSort()??><#if ctrl.getMinorSortPSAppDEField?? && ctrl.getMinorSortPSAppDEField()??><#assign sortableField = ctrl.getMinorSortPSAppDEField() /><#if sortableField.getName?? && sortableField.getName()??>sort:'${sortableField.getName()?lower_case},<#if ctrl.getMinorSortDir?? && ctrl.getMinorSortDir()??>${ctrl.getMinorSortDir()?lower_case}</#if>'</#if></#if></#if>};
    
    /**
    * 底部改变状态
    * 
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public handleBottomChange(status: String) {
    //   this.bottomStatus = status;
    }

    /**
    * 顶部改变状态
    * 
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public handleTopChange(status: String) {
    //   this.moveTranslate = 1;
    //   this.topStatus = status;
    }

    /**
     * 上拉加载更多数据
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public async loadBottom(): Promise<any> {
        this.pageNumber++;
        let params = {};
        if (this.viewparams) {
            Object.assign(params, this.viewparams);
        }
        Object.assign(params, { query: this.searchKey, page: this.pageNumber, size: this.pageSize });
        let response: any = await this.load(params, 'bottom');
        let loadmoreBottom: any = this.$refs.loadmoreBottom;
        if (loadmoreBottom) {
            loadmoreBottom.complete();
        }
    }

    /**
     * 删除
     *
     * @param {any[]} datas
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.name}')}
     */
    public async remove(datas: any[]): Promise<any> {
        let arg: any = {};
        let keys: Array<string> = [];
        let infoStr: string = '';
        datas.forEach((data: any, index: number) => {
            keys.push(data.${appde.getKeyPSAppDEField().getCodeName()?lower_case});
            if (index < 5) {
                if (!Object.is(infoStr, '')) {
                    infoStr += '、';
                }
                <#if appde.getMajorPSAppDEField()??>
                infoStr += data.${appde.getMajorPSAppDEField().getCodeName()?lower_case};
                <#else>
                infoStr += data.srfmajortext;
                </#if>
            }
        });
        if(datas.length <= 0 ){
          this.$notice.error('请选择至少一条删除~')
          return
        }
        if (datas.length < 5) {
            infoStr = infoStr + this.$t('app.message.totle') + datas.length + this.$t('app.message.data');
        } else {
            infoStr = infoStr + '...' + this.$t('app.message.totle') + datas.length + this.$t('app.message.data');
        }
        return new Promise((resolve, reject) => {
            const _remove = async () => {
                let _context: any = { ${appde.getCodeName()?lower_case}: keys.join(';') }
                const response: any = await this.service.delete(this.removeAction, Object.assign({}, this.context, _context), arg, this.showBusyIndicator);
                if (response && response.status === 200 && response.data.records) {
                    this.$notice.success((this.$t('app.message.deleteSccess') as string));
                    this.load();
                    this.closeSliding();
                    resolve(response);
                } else {
                    this.$notice.error(response.message?response.message:"删除失败");
                    reject(response);
                }
            }

            this.$dialog.confirm({
                title: (this.$t('app.message.warning') as string),
                message: this.$t('app.message.confirmToDelete') + infoStr +','+ this.$t('app.message.unrecoverable') + '？',
            }).then(() => {
                _remove();
            }).catch(() => {
            });
        });
    }

    /**
     * 刷新数据
     *
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.name}')}
     */
    public refresh(): Promise<any> {
        this.isLoading = true;
        return new Promise((resolve: any, reject: any) => {
            this.load().then((res) => {
                this.isLoading = false;
                resolve(res);
            }).catch((error: any) => {
                this.isLoading = false;
                reject(error);
            })
        })
    }

    /**
     * 长按
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public onPress(){
        let _this = this;
        window.addEventListener('contextmenu',(e:any)=>{
            _this.onCheackChange();
            e.preventDefault();
        });
    }

    /**
     * 长按状态改变事件
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public onCheackChange(){
        this.$emit('showCheackChange', !this.showCheack);
    }

    /**
     * 快速搜索
     *
     * @param {string} query
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public async quickSearch(query: string): Promise<any> {
        this.searchKey = query;
        this.pageNumber = 0;
        const response = await this.load(Object.assign({ query: query }, { page: this.pageNumber, size: this.pageSize }), "init");
        return response;
    }

    /**
     * 数据加载
     *
     * @private
     * @param {*} [data={}]
     * @param {string} [type=""]
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private async load(data: any = {}, type: string = ""): Promise<any> {
        if (!data.page) {
            Object.assign(data, { page: this.pageNumber });
        }
        if (!data.size) {
            Object.assign(data, { size: this.pageSize });
        }
        //部件排序
        if(this.sort){
​           Object.assign(data,this.sort);
        }
        //视图排序
        if(data.data && data.data.sort){
            Object.assign(data, { sort:data.data.sort });
        }
        const parentdata: any = {};
        this.$emit('beforeload', parentdata);
        Object.assign(data, parentdata);
        let tempViewParams:any = parentdata.viewparams?parentdata.viewparams:{};
        Object.assign(tempViewParams,JSON.parse(JSON.stringify(this.viewparams)));
        Object.assign(data,{viewparams:tempViewParams});
        const response: any = await this.service.search(this.fetchAction, this.context, data, this.showBusyIndicator);
        if (!response || response.status !== 200) {
            this.$notify({ type: 'danger', message: response.error.message });
            return response;
        }

        this.$emit('load', (response.data && response.data.records) ? response.data.records : []);
        this.pageTotal = response.data.total;
        if (type == 'top') {
            this.items = [];
            this.items = response.data.records;
        } else if (type == 'bottom') {
            for (let i = 0; i < response.data.records.length; i++) {
                this.items.push(response.data.records[i]);
            }
        } else {
            this.items = [];
            this.items = response.data.records;
        }
        this.items.forEach((item:any)=>{
            Object.assign(item,this.getActionState(item));    
        });
        return response;
    }

    /**
    * 全选
    *
    * @private
    * @param {*} [arg={}]
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    private handleClick() {
        this.items.forEach((item: any) => {
            item.value = true;
        });
        this.selectednumber = this.items.length;
    }

    /**
     * checkbox 选中回调
     *
     * @param {*} data
     * @returns
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public checkboxChange(data: any) {
        let { detail } = data;
        if (!detail) {
            return;
        }
        let { value } = detail;
        this.selectednumber = 0;
        this.items.forEach((item: any, index: number) => {
            if (item.value) {
                this.selectednumber++;
            }
            if (Object.is(item.${appde.getCodeName()?lower_case}id, value)) {
                if (detail.checked) {
                    this.selectdata.push(this.items[index]);
                } else {
                    this.selectdata.splice(this.selectdata.findIndex((i: any) => i.value === item.value), 1)
                }
            }
        });
        this.$emit('selectionchange', this.selectdata);
    }

    /**
     * 下拉刷新
     *
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public async pullDownToRefresh(): Promise<any> {
        this.pageNumber = 0;
        let params = {};
        if (this.viewparams) {
            Object.assign(params, this.viewparams);
        }
        Object.assign(params, { query: this.searchKey, pageNumber: this.pageNumber, pageSize: this.pageSize });
        let response: any = await this.load(params, 'top');
        return response;
    }

    /**
    * 点击回调事件
    *
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public item_click(item:any){
        if(this.showCheack){
            let count = this.selectedArray.findIndex((i) => {
            return i.mobentityid == item.mobentityid;
        });
            if (count === -1) {
                this.selectedArray.push(item);
            } else {
                this.selectedArray.splice(count, 1);
            }
        } else {
            this.goPage(item)
        }
    }

    /**
    * 点击列表数据跳转
    *
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public goPage(item: any) {
        this.$emit('rowclick',item);
    }

    /**
    * 获取多项数据
    *
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public getDatas(): any[] {
      return this.selectedArray;
    }

    /**
    * 获取单项数据
    *
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public getData(): any {
        return this.selectedArray[0];
    }

    /**
    * vue生命周期created
    *
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public created() {
        this.onPress();
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     *  @memberof ${srfclassname('${ctrl.codeName}')}
     */    
    protected afterCreated(){
        if (this.viewState) {
            this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(this.name, tag)) {
                    return;
                }
                if (Object.is(action, "load")) {
                    this.pageNumber = 0;
                    this.load(Object.assign(data, { page: this.pageNumber, size: this.pageSize }), "init");
                }
                if (Object.is(action, "search")) {
                    this.pageNumber = 0;
                    this.load(Object.assign(data, { page: this.pageNumber, size: this.pageSize }), "init");
                }
                if (Object.is(action, "quicksearch")) {
                    this.searchKey = data;
                    this.pageNumber = 0;
                    this.load(Object.assign({ query: data }, { page: this.pageNumber, size: this.pageSize }), "init");
                }
                if (Object.is(action, "refresh")) {
                    this.refresh();
                }
            });
        }
        <#if view.getViewType()?? && view.getViewType()=='DEMOBPICKUPMDVIEW'>
        if (!this.isMutli) {
            if (this.selectedData && this.selectedData.length > 0) {
                this.radio = this.selectedData[0].srfkey;
            }
        } else {
            if (this.selectedData && this.selectedData.length > 0) {
                this.checkboxList = [];
                this.selectedData.forEach((item: any) => {
                    this.checkboxList.push(item.srfkey);
                })
            }
        }
        </#if>
    }

    /**
     * vue 生命周期
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public destroyed() {
        this.afterDestroy();
    }

    /**
     * 执行destroyed后的逻辑
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected afterDestroy() {
        if (this.viewStateEvent) {
            this.viewStateEvent.unsubscribe();
        }
        window.removeEventListener('contextmenu',()=>{});
        <#if destroyed_block??>
        ${destroyed_block}
        </#if>
    }

    /**
     * 列表项左滑右滑触发行为
     *
     * @param {*} $event 点击鼠标事件
     * @param {*} tag 操作标识
     * @param {*} item 行数据
     * @memberof ${srfclassname('${ctrl.name}')}
     */
    public mdctrl_click($event: any, tag: any, item: any): void {
        $event.stopPropagation();
        this.selectedArray = [];
        this.selectedArray.push(item);
<#if ctrl.getPSDEUIActionGroup()?? && ctrl.getPSDEUIActionGroup().getPSUIActionGroupDetails()??>
<#assign details = ctrl.getPSDEUIActionGroup().getPSUIActionGroupDetails()>
<#list details as detail>
        if (Object.is(tag, '${detail.getName()}')) {
            this.mdctrl_${detail.getName()}_click();
        }
</#list>
</#if>
<#if ctrl.getPSDEUIActionGroup2()?? && ctrl.getPSDEUIActionGroup2().getPSUIActionGroupDetails()??>
<#assign details = ctrl.getPSDEUIActionGroup2().getPSUIActionGroupDetails()>
<#list details as detail>
        if (Object.is(tag, '${detail.getName()}')) {
            this.mdctrl_${detail.getName()}_click();
        }
</#list>
</#if>
        let curr :any = this.$refs[item.srfkey];
        curr[0].closeOpened();
    }

    /**
     * 单选选中变化
     * 
     * @memberof ${srfclassname('${ctrl.name}')}
     */
    public onSimpleSelChange(item: any = {}) {
        this.$emit('selectionchange', [item]);
        this.selectedValue = item.srfkey;
        this.selectedArray = [];
        this.goPage(item);
    }


   /**
     * 是否展示多选
     *
     * @memberof Mdctrl
     */
    @Prop({default:false}) showCheack?: boolean;

    /**
     * 选中或取消事件
     *
     * @memberof ${srfclassname('${ctrl.name}')}
     */
    public checkboxSelect(item:any){
        let count = this.selectedArray.findIndex((i) => {
            return i.${appde.getKeyPSAppDEField().getCodeName()?lower_case} == item.${appde.getKeyPSAppDEField().getCodeName()?lower_case};
        });
        let re = false;
        if(count == -1){
            re = true;
            this.selectedArray.push(item);
        }else{
            this.selectedArray.splice(count,1);
        }
        this.items.forEach((_item:any,index:number)=>{
            if(_item.${appde.getKeyPSAppDEField().getCodeName()?lower_case} == item.${appde.getKeyPSAppDEField().getCodeName()?lower_case}){
                this.items[index].checked = re;
            }
        });
    }
    
    /**
     * 全选事件
     *
     * @memberof ${srfclassname('${ctrl.name}')}
     */
    public checkboxAll(item:any) {
        this.selectAllIschecked = item.detail.checked;
        if(this.selectAllIschecked){
            this.selectedArray = JSON.parse(JSON.stringify(this.items));
        }else{
            this.selectedArray = [];
        }
        this.items.forEach((item:any,index:number)=>{
            this.items[index].checked = this.selectAllIschecked
        });
        this.$forceUpdate();
    }


    /**
     * 全选按钮选中状态
     *
     * @memberof ${srfclassname('${ctrl.name}')}
     */
    public selectAllIschecked = false;


    /**
     * 关闭滑动项
     *
     * @memberof Mdctrl
     */
    public closeSliding(){
        let sliding :any = this.$refs.sliding;
        if(sliding){
            sliding.forEach((item:any) => {
                item.closeOpened();
            });
        }
    }

    /**
     * 界面行为模型
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */  
    public ActionModel:any ={
    <#if ctrl.getPSUIActions()??>
    <#list ctrl.getPSUIActions() as item>
        ${item.getUIActionTag()}: { name: '${item.getUIActionTag()}',disabled: false, visabled: true,noprivdisplaymode:<#if item.getNoPrivDisplayMode(view)??>${item.getNoPrivDisplayMode(view)}</#if>,dataaccaction: '<#if item.getDataAccessAction()??>${item.getDataAccessAction()}</#if>', target: '${item.getActionTarget()}'}<#if item_has_next>,</#if>
    </#list>
    </#if>  
    };

    /**
     * 获取界面行为权限状态
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public getActionState(data:any){
        //let targetData:any = this.transformData(data);
        let tempActionModel:any = JSON.parse(JSON.stringify(this.ActionModel));
        this.$viewTool.calcActionItemAuthState(data,tempActionModel,this.deUIService);
        return tempActionModel;
    }
<#ibizinclude>
../@MACRO/CONTROL/CONTROL_BOTTOM-BASE.vue.ftl
</#ibizinclude>

<#ibizinclude>
../@MACRO/CONTROL/CONTROL-BASE.style.ftl
</#ibizinclude>